<?php

namespace app\admin\pattern\strategy\login;

use app\admin\model\Administrator;

trait LoginTrait
{
	public function doPasswordLogin(string $sign,string $password,string $type = '')
	{
		if (empty($sign)) {
			return responseData(400, $type.' is not empty!');
		}
		if (empty($password)) {
			return responseData(400,'password is not empty!');
		}
		//TODO 邮箱登录时获取不到用户信息
		$user = Administrator::getUserByWhere([$type => $sign]);
		//检测用户名是否存在
		if (!$user || $user->isEmpty()){
			return responseData(400,"{$type} [{$sign}] is not exist!");
		}
		if (!password_verify($password,$user->password)) {
			return responseData(400,'password is not correct!',);
		}
        if ($user->status == 0) {
            return responseData(404,'administrator is not active!');
        }
		// 重新生成加密密码
		$user->password = password_hash($password,PASSWORD_DEFAULT);
		// 生成token
		$token = generateToken();
		// 更新token
		$user->token = $token;
        $user->last_login_time = time();
        $user->last_login_ip = request()->ip();
		// 更新token过期时间
		$user->token_expire = time() + config('app.token_expire');
		if(!$user->save()) {
			return responseData(500,'login failed!');
		}
		return responseData(['token' => $token]);
	}

}